package org.wu.framework.lazy.orm.core.persistence.format;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

public abstract class AbstractFormatMapper implements FormatMapper {

    /**
     * 格式化
     *
     * @param pattern 文件数据
     * @param param   参数
     */
    @Override
    public String format(String pattern, Object param) {
        Map<String, Object> map = new HashMap<>();
        if (param == null) {
            return pattern;
        } else if (param instanceof Map) {
            map = (Map<String, Object>) param;
        } else {
            // 获取对象属性
            for (Field declaredField : param.getClass().getDeclaredFields()) {

                try {
                    declaredField.setAccessible(true);
                    String k = declaredField.getName();
                    Object v = declaredField.get(param);
                    map.put(k, v);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        for (Map.Entry<String, Object> stringObjectEntry : map.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            if (value == null) {
                continue;
            }
            String target = "#\\{" + key + "}";
            Object replacement = value;
            if (AtomicReference.class.isAssignableFrom(value.getClass())) {
                replacement = ((AtomicReference<?>) value).get();
            }
            pattern = pattern.replaceAll(target, replacement.toString());

        }
        return pattern;
    }
}
